package com.ywy.chat.server;

import cn.hutool.json.JSONUtil;
import com.ywy.chat.ChatConstants;
import com.ywy.chat.handler.MsgHandler;
import com.ywy.chat.handler.MsgHandlerFactory;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.server.handler.IWsMsgHandler;

import java.util.Map;

/**
 * 群聊消息处理类
 *
 * @author ywy
 * @date 2021/12/31 14:10
 */
@Slf4j
public class WsMsgHandler implements IWsMsgHandler {
    /**
     * 握手前操作
     * @param httpRequest
     * @param httpResponse
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        String userId = httpRequest.getParam("userId");
        // 绑定用户信息
        Tio.bindUser(channelContext, userId);
        log.info("WsMsgHandler----->用户上线：{}", userId);
        return httpResponse;
    }

    /**
     * 握手后操作
     * @param httpRequest
     * @param httpResponse
     * @param channelContext
     * @throws Exception
     */
    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        // 绑定群组
        Tio.bindGroup(channelContext, ChatConstants.GROUP_NAME);
    }

    /**
     * 字节消息处理
     * @param wsRequest
     * @param bytes
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    /**
     * 字符消息处理
     * @param wsRequest
     * @param text
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
        if(text != null && text.indexOf("ping") < 0) {
            log.info("WsMsgHandler----->接收到消息：{}", text);
        }
        // 解析消息
        Map map = JSONUtil.toBean(text, Map.class);
        String type = map.get("type").toString();
        String data = map.get("data").toString();
        // 获取消息处理器
        MsgHandler msgHandler = MsgHandlerFactory.getMsgHandler(type);
        msgHandler.handler(data, wsRequest, channelContext);
        return null;
    }

    /**
     * 关闭连接
     * @param wsRequest
     * @param bytes
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        log.info("WsMsgHandler----->用户退出群聊：{}", channelContext.userid);
        return null;
    }
}
